package com.rongshu.sendmessage.util.wx;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rongshu.sendmessage.activity.MainActivity;
import com.rongshu.sendmessage.base.MyApplication;
import com.rongshu.sendmessage.bean.HuoYunBean;
import com.rongshu.sendmessage.util.ClientPublicParamUtil;
import com.rongshu.sendmessage.util.StringUtils;
import com.rongshu.sendmessage.util.httpUtil.HYContent;
import com.rongshu.sendmessage.util.httpUtil.IModel;
import com.rongshu.sendmessage.util.notifi.NotificationUtil;
import com.rongshu.sendmessage.util.wx.Constant_Third_ID;

import org.json.JSONException;

import java.util.HashMap;
import java.util.Map;

public class WChartUtil {
    public static void getWChartToken(String code, Context mContext,IWchartLogin loginOver){
        String uri = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" + Constant_Third_ID.weixin_app_id +
                "&secret=" + Constant_Third_ID.weixin_app_secret +
                "&code=" + code + "&grant_type=authorization_code";
        OkGo.<String>get(uri).
                tag("GETweinxininfoaccess_token")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            WXAccessTokenEntity accessTokenEntity = JSON.parseObject(response.body(), WXAccessTokenEntity.class);
                            if (accessTokenEntity != null) {
                                getUserInfo(accessTokenEntity);
                            } else {
                                Log.d("DONG", "获取失败");
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {

                    }
                    /**
                     * 获取个人信息
                     *
                     * @param accessTokenEntity
                     */
                    private void getUserInfo(WXAccessTokenEntity accessTokenEntity) {

                        String uri = "https://api.weixin.qq.com/sns/userinfo" +
                                "?access_token=" + accessTokenEntity.getAccess_token()
                                + "&openid=" +accessTokenEntity.getOpenid()
                                +"&clientPublicParam="+ ClientPublicParamUtil.getPublicParams(mContext);
                        OkGo.<String>get(uri).
                                tag("GETweinxinuserinfo")
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(Response<String> response) {
                                        try {
                                            operatePresenter(response.body());
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void onError(Response<String> response) {

                                    }
                                });
                    }
                    private void operatePresenter(String wxLoginStr) {
                        Map<String, String> param = new HashMap<String, String>();
                        param.put("wxuserJson", wxLoginStr);
                        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
                        OkGo.<String>post(new HYContent().WX_LOGIN_URL).params(param).execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {

                                //Driver司机，VehicleOwner车主
                                IModel.AjaxResult jr = new IModel.AjaxResult(response.body(),false);
                                Log.d("user", response.body());
                                String state = jr.getStatus();
                                HuoYunBean huoYunBean = null;
                                String officeName="noOffice";
                                if ("success".equals(state)) {
                                    huoYunBean = com.alibaba.fastjson.JSONObject.toJavaObject(jr.getData(), HuoYunBean.class);
                                    if (huoYunBean != null) {
                                        huoYunBean.setLoginName("");
                                        huoYunBean.setPassword("");
                                        HYContent.saveUser(huoYunBean);

                                        try {
                                            org.json.JSONObject jsonObject = new org.json.JSONObject(huoYunBean.getUserIdentitys());
                                            String typeUser = jsonObject.getString("hybUserIdentity");
                                            MyApplication.editor.putString(HYContent.USET_TYPE, typeUser);
                                            String oldType = MyApplication.mSettings.getString(HYContent.USET_OLD_TYPE, "VehicleOwner");
                                            Intent intent = new Intent(mContext, MainActivity.class);
                                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                            intent.putExtra("message","login");
                                            mContext.startActivity(intent);
                                            loginOver.onSuccess();
                                            //设置极光推送的tag标签和昵称
                                            new NotificationUtil().setTag(mContext,officeName);
                                            new NotificationUtil().setAlias(mContext,huoYunBean.getNickName());
                                        } catch (JSONException e) {
                                            Intent intent = new Intent(mContext, MainActivity.class);
                                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                            intent.putExtra("message","login");
                                            mContext.startActivity(intent);
                                            loginOver.onSuccess();
                                        }
                                    }
                                }
                            }
                            @Override
                            public void onError(Response<String> response) {
                            }
                        });

                    }
                });

    }

    // 登陆的是从对话框过来的需要通知对话框，我注册完了。需要刷新页面
    public interface IWchartLogin{
        void onSuccess();
        void onError();
    }
}
